import React, { useLayoutEffect } from "react";
import { useElement } from "./context";
//表单元素组件
function FormItem(props) {
  const { state, dispatch } = useElement();
  const { children, name, title, tipClass, required, style = {} } = props;
  const { [name]: inputValue } = state;

  useLayoutEffect(() => {
    required && dispatch({
      type: 'changeValue',
      payload: {
        [name]: undefined,
      }
    })
  }, [dispatch, name, required])

  const onChange = (e) => {
    const { target: { value } } = e;
    dispatch({
      type: 'changeValue',
      payload: {
        [name]: value,
      }
    })
  }
  return (
    <div style={{ width: '100%', marginTop: '1rem', ...style }}>

      {typeof children == 'object' && React.cloneElement(
        children,
        {
          value: typeof inputValue == "string" ? inputValue : '',
          onChange,
          placeholder: `请输入${title}...`,
        })
      }

      {
        typeof children == 'function' && children({
          state,
          value: typeof inputValue == "string" ? inputValue : '',
          onChange,
          placeholder: `请输入${title}...`,
        })
      }

      {typeof inputValue == "string" &&
        (!inputValue) &&
        required &&
        <div className={tipClass}>
          {`请输入${title}`}
        </div>}
    </div>
  )
}
export default FormItem;